<template>
<div>
  <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <ul class="nav nav-tabs ll-box ll-nav">
    <li role="presentation" ><a href="/#/imex">商品信息</a></li>
    <li role="presentation" class="active"><a href="/#/customer">公司信息</a></li>
  </ul>
  <div class="row ll-head">
    <div class="ll-box ll-btn-group">
      <div class="col-md-1">
        <i class="glyphicon glyphicon-save"></i>导入
        <input type="file" @change="importExcel($event.target)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
      </div>
      <div class="col-md-1" @click="downloadExl()"><i class="glyphicon glyphicon-open"></i>导出</div>
      <!-- <div class="col-md-1" @click="submit()"><i class="glyphicon glyphicon-send"></i>提交</div> -->
    </div>
  </div>
  <div class="ll-box">
    <!-- <div class="ll-sech">
      <div class="row inputbox">
        <div class="col-md-4">
          <input type="text" class="form-control" placeholder="客户名称">
        </div>
        <div class="col-md-4">
          <div class="col-md-1"><div class="btn btn-primary btn-sech"><i class="glyphicon glyphicon-search"></i>查询</div></div>
        </div>
      </div>
    </div> -->
    <div class="list-tip">您当前共有<em class="num">{{tableTbody.length}}</em>条客户资料信息</div>
    <table class="table table-hover table-condensed ll-table">
      <thead>
        <tr>
          <th v-for="(item,index) in tableHeader">{{item}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row,index) in tableTbody">
          <td v-for="col in tableHeader">{{row[col]}}</td>
        </tr>
      </tbody>
    </table>
  </div>
  <a href="" download="客户资料.xlsx" id="hf"></a>
</div>
</template>
<script>
export default {
  name: "exim",
  data() {
    return {
      wb: "",
      tableHeader: ["行号","客户名称","省", "市", "区", "详情地址", "客户类型", "机构等级", "联系人", "联系电话"],
      tableTbody: [],
    };
  },
  created(){
    if(!localStorage.userinfo){
      this.$router.push({
        path:'/lllogin'
      })
    }
  },
  methods: {
    importExcel(obj) {
      if (!obj.files) {
        return;
      }
      let file = obj.files[0],
        types = file.name.split(".")[1],
        fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
          item => item === types
        );
      if (!fileType) {
        alert("格式错误！请重新选择");
        return;
      }
      this.file2Xce(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          // var listNeedFill = ['客户名称','客户类型','联系人','联系电话'];
          //this.tableHeader = Object.keys(tabJson[0]);
          // console.log(tabJson)
          // for(var i = 0; i < tabJson.length; i++){
          //   for(var k = 0; k < listNeedFill.length; k++){
          //     if(!tabJson.hasOwnProperty(listNeedFill[k])){
          //     }
          //   }
          // }
          // console.log(tabJson)
          for(var i = 0; i < tabJson.length; i++){
            tabJson[i]['行号'] = i+1;
          }
          this.tableTbody = tabJson;
          this.submit();
        }
      });
    },
    file2Xce(file) {
      var self = this;
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        reader.onload = function(e) {
          let data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          resolve(
            XLSX.utils.sheet_to_json(this.wb.Sheets[this.wb.SheetNames[0]])
          );
        };
        reader.readAsBinaryString(file);
      });
    },

    downloadExl() {
      var tmpDown; //导出的二进制对象
      var jsonarr;
      if (this.tableTbody.length == 0) {
        jsonarr = [{
          "客户名称":'',
          "省":'', 
          "市":'',
          "区":'', 
          "详情地址":'',
          "客户类型":'',
          "机构等级":'',
          "联系人":'',
          "联系电话":''
        }];
      }else{
        jsonarr = this.tableTbody;
      };
      var self = this;
      downloadExl(jsonarr);
      var self = this;
      function downloadExl(json, type) {
        var tmpdata = json[0];
        json.unshift({});
        var keyMap = []; //获取keys
        for (var k in tmpdata) {
          keyMap.push(k);
          json[0][k] = k;
        }
        var tmpdata = []; //用来保存转换好的json
        json
          .map((v, i) =>
            keyMap.map((k, j) =>
              Object.assign(
                {},
                {
                  v: v[k],
                  position:
                    (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) +
                    (i + 1)
                }
              )
            )
          )
          .reduce((prev, next) => prev.concat(next))
          .forEach(
            (v, i) =>
              (tmpdata[v.position] = {
                v: v.v
              })
          );
        var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
        var tmpWB = {
          SheetNames: ["mySheet"], //保存的表标题
          Sheets: {
            mySheet: Object.assign(
              {},
              tmpdata, //内容
              {
                "!ref": outputPos[0] + ":" + outputPos[outputPos.length - 1] //设置填充区域
              }
            )
          }
        };
        tmpDown = new Blob(
          [
            s2ab(
              XLSX.write(
                tmpWB,
                {
                  bookType: type == undefined ? "xlsx" : type,
                  bookSST: false,
                  type: "binary"
                } //这里的数据是用来定义导出的格式类型
              )
            )
          ],
          {
            type: ""
          }
        ); //创建二进制对象写入转换好的字节流
        var href = URL.createObjectURL(tmpDown); //创建对象超链接
        document.getElementById("hf").href = href; //绑定a标签
        document.getElementById("hf").click(); //模拟点击实现下载
        setTimeout(function() {
          //延时释放
          URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()来释放这个object URL
        }, 100);
        json.splice(0, 1);
      }
      function s2ab(s) {
        //字符串转字符流
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
      function getCharCol(n) {
        let temCol = "",
          s = "",
          m = 0;
        while (n > 0) {
          m = n % 26 + 1;
          s = String.fromCharCode(m + 64) + s;
          n = (n - m) / 26;
        }
        return s;
      }
    },
    submit() {
      var self = this;
      if (this.tableTbody.length == 0) {
        self.Toast({
          message: "请导入客户信息！"
        });
        return false;
      }
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        TenantGuid: userinfo.TenantGUID,
        CorpGuid: userinfo.CorpGuid,
        StaffID: userinfo.StaffID,
        Name: userinfo.Name,
        ImportMfMed: this.tableTbody
      };
      this.Ajax.post("ImportMfmed", query ,'导入中').then(function(resp) {
        console.log(resp)
        alert(resp.ErrorMessage);
        // if (resp.IsSuccess) {
        //   self.Toast({
        //     message: resp.ErrorMessage
        //   });
        // } else {
        //   self.Toast({
        //     message: resp.ErrorMessage
        //   });
        // }
      });
    }
  }
};
</script>